﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CILtoNative
{
    internal class PlugManager
    {
        public Dictionary<string, PluggerWrapper> CodePlugs;

        public void SetupAndLoad()
        {
            CodePlugs = new Dictionary<string, PluggerWrapper>();
            PlugBridge bridge = new PlugBridge() { toManage = this };
            foreach (string plugger in System.IO.Directory.GetFiles(System.IO.Path.Combine(global.AppDir, "plugs")))
            {
                if (plugger.EndsWith(".dll"))
                {
                    Assembly newAssembly = Assembly.LoadFile(plugger);
                    Type[] types = newAssembly.GetExportedTypes();
                    foreach (var type in types)
                    {
                        if (type.IsClass && (type.GetInterface(typeof(CodePlug).FullName) != null))
                        {
                            ((CodePlug)Activator.CreateInstance(type)).SetupListeners(bridge);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Adds a plug with its plugger to the Manager
        /// </summary>
        /// <param name="plug">Call to plug</param>
        /// <param name="plugger">Plugger to plug code</param>
        /// <returns>False if error occured</returns>
        public bool AddPlug(string plug, PluggerWrapper plugger)
        {
            if (!CodePlugs.ContainsKey(plug))
            {
                CodePlugs.Add(plug, plugger);
                return true;
            }
            else
            {
                return false;
            }
        }

        public int GetArgsNeeded(string Input)
        {
            if (CodePlugs.ContainsKey(Input))
            {
                return CodePlugs[Input].Arguments;
            }
            return -1;
        }

        public string PlugUpCode(string Input, List<object> Args)
        {
            if (CodePlugs.ContainsKey(Input))
            {
                return CodePlugs[Input].Plugger.PlugCode(Input, Args);
            }
            return string.Empty;
        }
    }
}
